<?php
declare (strict_types=1);

namespace app\common\model;

use Exception;
use think\Collection;

class FeedbackContent extends CommonBase
{
    public const STATUS_NAME_MAP = [1 => '等待审核', '2' => '审核通过', 3 => '审核拒绝'];

    public function __construct(array $data = [], string $connection = 'mysql', string $name = '')
    {
        parent::__construct($data);
        $this->connection = $connection;
        $this->name       = $name;
    }

    public function getFeedbackContentList(int $page = 1, int $limit = 10, array $where = []): Collection
    {
        $where['is_delete'] = config('status.mysql.table_normal');
        $offset             = ($page - 1) * $limit;
        return $this->where($where)->order('created_at desc')->limit($offset, $limit)->select();
    }

    public function getFeedbackContentCount(array $where = []): int
    {
        $where['is_delete'] = config('status.mysql.table_normal');
        return $this->where($where)->count();
    }

    public function findFeedbackContentById(int $id, int $formId): array
    {
        // 留言主要内容
        $feedbackContentObj = $this->where(['id' => $id, 'is_delete' => config('status.mysql.table_normal')])->find();
        if (empty($feedbackContentObj)) {
            return [];
        }
        $feedbackContent = $feedbackContentObj->toArray();

        // 留言表单标识
        $feedbackFormObj = $this->name('feedback_form')->where([
            'id'        => $formId,
            'status'    => self::IS_ENABLE_STATUS,
            'is_delete' => config('status.mysql.table_normal'),
        ])->find();
        if (empty($feedbackFormObj)) {
            return [];
        }
        $feedbackForm = $feedbackFormObj->toArray();

        // 留言表单字段
        $feedbackFieldObj = $this->name('feedback_field')->where([
            'form_id'   => $formId,
            'status'    => self::IS_ENABLE_STATUS,
            'is_delete' => config('status.mysql.table_normal'),
        ])->order('sort asc')->select();

        $feedbackFields = $feedbackFieldObj->toArray();
        foreach ($feedbackFields as $field) {
            $feedbackContentExtend = [];
            $fieldValue            = '';

            if ($field['is_system'] == self::FIELD_IS_CUSTOMER) {
                $tableName = 'feedback_' . $feedbackForm['form_code'] . '_' . self::FIELD_TYPE_DB_SUFFIX_MAP[$field['field_type']];

                $whereExtend              = [
                    'feedback_id' => $id,
                    'field_id'    => $field['id'],
                    'is_delete'   => config('status.mysql.table_normal'),
                ];
                $feedbackContentExtendObj = $this->name($tableName)->where($whereExtend)->find();
                if (!empty($feedbackContentExtendObj)) {
                    $feedbackContentExtend = $feedbackContentExtendObj->toArray();
                    $fieldValue            = $feedbackContentExtend['field_value'];
                }
            }

            switch ($field['code']) {
                case 'title':
                    $fieldValue = $feedbackContent['title'];
                    break;
                case 'status':
                    $fieldValue = $feedbackContent['status'];
                    break;
                case 'created_at':
                    $fieldValue = $feedbackContent['created_at'];
                    break;
            }

            $feedbackContent['feedback_fields'][] = [
                'field_id'    => $field['id'],
                'field_type'  => $field['field_type'],
                'field_code'  => $field['code'],
                'field_value' => $fieldValue,
                'field_name'  => $field['name'],
            ];
        }

        return $feedbackContent;
    }

    public function updateFeedbackContent(int $id, array $data): bool
    {
        $data['updated_at'] = date('Y-m-d H:i:s');
        return (boolean)$this->where(['id' => $id])->save($data);;
    }

    /**
     * @throws Exception
     */
    public function deleteFeedbackContent(int $id, int $formId): bool
    {
        try {
            $this->startTrans();
            // 留言表单标识
            $feedbackFormObj = $this->name('feedback_form')->where([
                'id'        => $formId,
                'status'    => self::IS_ENABLE_STATUS,
                'is_delete' => config('status.mysql.table_normal'),
            ])->find();
            if (empty($feedbackFormObj)) {
                throw new Exception('get feedback form error');
            }
            $feedbackForm = $feedbackFormObj->toArray();

            // 留言表单字段
            $feedbackFieldObj = $this->name('feedback_field')->where([
                'form_id'   => $formId,
                'is_delete' => config('status.mysql.table_normal'),
            ])->select();
            $feedbackFields   = $feedbackFieldObj->toArray();

            // 删除扩展数据
            foreach ($feedbackFields as $field) {
                if ($field['is_system'] == self::FIELD_IS_SYSTEM) {
                    continue;
                }

                $tableName   = 'feedback_' . $feedbackForm['form_code'] . '_' . self::FIELD_TYPE_DB_SUFFIX_MAP[$field['field_type']];
                $whereExtend = [
                    'feedback_id' => $id,
                    'field_id'    => $field['id'],
                    'is_delete'   => config('status.mysql.table_normal'),
                ];
                $this->name($tableName)->where($whereExtend)->update(['is_delete' => config('status.mysql.table_delete')]);
            }

            // 删除主表数据
            $this->where(['id' => $id])->save([
                'is_delete'  => config('status.mysql.table_delete'),
                'updated_at' => date('Y-m-d H:i:s'),
            ]);

            $this->commit();
            return true;
        } catch (Exception $e) {
            $this->rollback();
            throw new Exception($e->getMessage());
        }
    }

    /**
     * @throws Exception
     */
    public function batchDeleteFeedbackContent(array $ids, int $formId): bool
    {
        try {
            $this->startTrans();
            // 留言表单标识
            $feedbackFormObj = $this->name( 'feedback_form')->where([
                'id'        => $formId,
                'status'    => self::IS_ENABLE_STATUS,
                'is_delete' => config('status.mysql.table_normal'),
            ])->select();
            $feedbackForm    = $feedbackFormObj->toArray();

            // 留言表单字段
            $feedbackFieldObj = $this->name( 'feedback_field')->where([
                'form_id'   => $formId,
                'is_delete' => config('status.mysql.table_normal'),
            ])->find();
            if (empty($feedbackFieldObj)) {
                throw new Exception('get feedback form fields error');
            }
            $feedbackFields = $feedbackFieldObj->toArray();

            foreach ($ids as $id) {
                // 删除扩展数据
                foreach ($feedbackFields as $field) {
                    if ($field['is_system'] == self::FIELD_IS_SYSTEM) {
                        continue;
                    }

                    $tableName   = 'feedback_' . $feedbackForm['form_code'] . '_' . self::FIELD_TYPE_DB_SUFFIX_MAP[$field['field_type']];
                    $whereExtend = [
                        'feedback_id' => $id,
                        'field_id'    => $field['id'],
                        'is_delete'   => config('status.mysql.table_normal'),
                    ];
                    $this->name($tableName)->where($whereExtend)->update([
                        'is_delete'  => config('status.mysql.table_delete'),
                        'updated_at' => date('Y-m-d H:i:s'),
                    ]);
                }
            }

            // 删除主表数据
            $this->where([['id', 'in', $id]])->save([
                'is_delete'  => config('status.mysql.table_delete'),
                'updated_at' => date('Y-m-d H:i:s'),
            ]);

            $this->commit();
            return true;
        } catch (Exception $e) {
            $this->rollback();
            throw new Exception($e->getMessage());
        }
    }

    /**
     * @throws Exception
     */
    public function addFeedbackContent(string $formCode, array $data): bool
    {
        try {
            $this->startTrans();

            $this->save([
                'is_delete' => config('status.mysql.table_normal'),
                'status'    => self::IS_ENABLE_STATUS,
                'title'     => $data['title'],
            ]);
            $feedbackId = $this->getLastInsID();

            // 留言表单
            $feedbackFormObj = $this->name( 'feedback_form')->where([
                'form_code' => $formCode,
                'status'    => self::IS_ENABLE_STATUS,
                'is_delete' => config('status.mysql.table_normal'),
            ])->find();
            if (empty($feedbackFormObj)) {
                throw new Exception('get feedback form error');
            }

            $feedbackForm = $feedbackFormObj->toArray();
            $formId       = $feedbackForm['id'];

            // 留言表单字段
            $feedbackFieldObj = $this->name( 'feedback_field')->where([
                'form_id'   => $formId,
                'status'    => self::IS_ENABLE_STATUS,
                'is_delete' => config('status.mysql.table_normal'),
            ])->select();

            $feedbackFields = $feedbackFieldObj->toArray();
            foreach ($feedbackFields as $field) {
                if ($field['is_system'] == self::FIELD_IS_SYSTEM) {
                    continue;
                }

                $tableName = 'feedback_' . $feedbackForm['form_code'] . '_' . self::FIELD_TYPE_DB_SUFFIX_MAP[$field['field_type']];
                $this->name($tableName)->insert([
                    'field_id'    => $field['id'],
                    'feedback_id' => $feedbackId,
                    'field_value' => $data['extend_fields'][$field['code']] ?? '',
                    'is_delete'   => config('status.mysql.table_normal'),
                    'created_at'  => date('Y-m-d H:i:s'),
                    'updated_at'  => date('Y-m-d H:i:s'),
                ]);
            }

            $this->commit();
            return true;

        } catch (\Exception $e) {
            $this->rollback();
            throw new Exception($e->getMessage());
        }
    }

    public function batchDoCheck(array $ids, int $status): bool
    {
        return (boolean)$this->where([['id', 'in', $ids]])->save([
            'status'     => $status,
            'updated_at' => date('Y-m-d H:i:s'),
        ]);
    }
}